import android,sys,time,socket

droid = android.Android()

dictstations = {}

dictstations['Absolute Radio 90s'] = {'URL':'http://absolute.radio','Description':'90s Stuff'}
dictstations['Zeilsteen'] = {'URL':'http://live.zeilsteen.com','Description':'Dutch Internet Radio'}

itemlist = []

RECV_SIZE = 2**20

for item in dictstations:
  itemlist.append(item)

itemlist.append('Stop playing')

def openconnection(host,port):
  s = None
  try:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    droid.makeToast('Connecting to %s:%d...' % (host,port))
    s.connect((host,port))
    droid.makeToast('Connected.')
  except socket.error:
    droid.makeToast('Unable to connect')
    sys.exit(1)
 
  return s
  
def play(skt,url):
  skt.send('clear' +'\n')
  droid.makeToast(skt.recv(RECV_SIZE))
  droid.makeToast('Cleared')
  skt.send('add ' + url + '\n')
  droid.makeToast(skt.recv(RECV_SIZE))
  skt.send('play' + '\n')
  droid.makeToast(skt.recv(RECV_SIZE))

def stop(skt):
  skt.send('clear' + '\n')
  droid.makeToast(skt.recv(RECV_SIZE))
  
def getlist():
  droid.dialogCreateAlert("Choose Station or stop")
  #droid.dialogSetItems(["Absolute Radio 90s","Zeilsteen", "Stop playing"])
  droid.dialogSetItems(itemlist)
  droid.dialogShow()
  result=droid.dialogGetResponse().result
  if result.has_key("item"):
    return result["item"]
  else:
    return -1

list=getlist()
if list<0:
  print "No item chosen"
  sys.exit()

#Get the url of the selected item

droid.makeToast("Here")
droid.makeToast(str(list))

sock = openconnection('192.168.0.29',6600)

#droid.makeToast(str(dictstations[list]))

if ((list + 1) > len(dictstations)):
  droid.makeToast('Stop Playing')
  stop(sock)
  sys.exit()

url = dictstations[itemlist[list]]['URL']

#Add the url to the playlist and play

play(sock,url)

sock.close()

